<template>
  <div class="">
    <el-row>
      <el-col :span="24">
        <div class="page-filter mb10 fl">
          <el-form ref="filter" :model="filter" label-width="0">
            <el-form-item class="mr10 mb5 fl">
              <ProFilter v-model="filter.pro_id" />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl">
              <PurchaseSelect v-model="filter.pur_id" />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl">
              <SupplierSelect v-model="filter.sup_id" />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl">
              <EntrustSel v-model="filter.entrust_id" />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl" prop="year">
              <el-date-picker
                v-model="filter.year"
                placeholder="年度"
                type="year"
                format="yyyy"
                value-format="yyyy"
                size="small"
                clearable
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl" prop="begin_time">
              <el-date-picker
                v-model="filter.begin_time"
                placeholder="开始时间"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="small"
                clearable
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl" prop="end_time">
              <el-date-picker
                v-model="filter.end_time"
                placeholder="结束时间"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="small"
                clearable
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl" style="width: 300px">
              <el-button
                size="small"
                @click="app.resetFields($refs['filter'].$parent, 'filter')"
                >清 空</el-button
              >
              <el-button type="primary" size="small" @click="getList"
                >查 询</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="24">
        <el-row>
          <el-col :span="24" class="h240 pr">
            <div class="m-left pa l0 t0 h200 fs16">
              <div class="m-left-title mt15" style="background-color: blue">
                <div>{{ filter.year ? filter.year : '本年' }}采购</div>
                <div class="fs20 fw600 mt5">{{ this.yearAmount }}</div>
              </div>
              <div class="m-left-title mt15" style="background-color: cyan">
                <div>当月采购</div>
                <div class="fs20 fw600 mt5">{{ this.monthAmount }}</div>
              </div>
            </div>
            <div class="m-center w100 h240">
              <div id="ba" style="width: 100%; height: 240px" />
            </div>
            <div class="m-right pa r0 t0 h220">
              <div id="bn" style="width: 100%; height: 220px" />
            </div>
          </el-col>
        </el-row>
        <el-table
          v-loading="app.loading"
          class="search-table"
          :data="list"
          border
          :summary-method="getSummaries"
          show-summary
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="序号" align="center" width="56px">
            <template slot-scope="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            label="签订公司"
            width="220px"
            :formatter="formatterCompany"
          />
          <el-table-column label="PO单号" width="190px">
            <template slot-scope="{ row }">
              {{ 'PO' + row.pro_id }}
            </template>
          </el-table-column>
          <el-table-column label="项目名称" min-width="220px" prop="pro_name" />
          <el-table-column
            label="采购日期"
            align="center"
            width="140px"
            prop="pur_time"
          />
          <el-table-column label="供应商名称" min-width="220px">
            <template slot-scope="{ row }">
              {{ row.sup_name ? row.sup_name : '仓库' }}
            </template>
          </el-table-column>
          <el-table-column label="采购金额" align="right" width="140px">
            <template slot-scope="{ row }">
              {{ app.toFix(row.price, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="已付款金额" align="right" width="140px">
            <template slot-scope="{ row }">
              {{ app.toFix(row.pay, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="未付款金额" align="right" width="140px">
            <template slot-scope="{ row }">
              {{ app.toFix(row.price - row.pay, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="追加金额" align="right" width="140px">
            <template slot-scope="{ row }">
              {{ app.toFix(row.additional, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="追减金额" align="right" width="140px">
            <template slot-scope="{ row }">
              {{ app.toFix(row.reduction, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="已开票金额" align="right" width="140px">
            <template slot-scope="{ row }">
              {{ app.toFix(row.has_tax, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="未开票金额" align="right" width="140px">
            <template slot-scope="{ row }">
              {{
                app.toFix(
                  app.toFix(row.price, 2) - app.toFix(row.has_tax, 2),
                  2
                )
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="采购类型"
            align="center"
            width="90px"
            :formatter="formatterType"
          />
          <el-table-column label="备注" min-width="220px" prop="remark" />
        </el-table>
        <pagination
          v-show="filter.pageAll > 0"
          :total="filter.pageAll"
          :page.sync="filter.pageCurrent"
          :limit.sync="filter.pageNumber"
          @pagination="getList"
        />
      </el-col>
      <!-- <el-col :span="12" class="mt20">
        <div id="ba" style="width: 95%;height:400px;" />
      </el-col>
      <el-col :span="12" class="mt20">
        <div id="bn" style="width: 95%;height:400px;" />
      </el-col> -->
    </el-row>
    <Dialog ref="dialog" :info="dialog" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { purchases, purchaseTotalAmount } from '@/api/statistics/statistics'
import page from '@/utils/page'
import SupplierSelect from '@/myComponents/SupplierSelect'
import PurchaseSelect from '@/myComponents/PurchaseSelect'
import EntrustSel from '@/myComponents/EntrustSel'
import ProFilter from '@/components/ProFilter'
import Dialog from './components/monthly-dialog'

export default {
  name: '',
  components: { SupplierSelect, PurchaseSelect, EntrustSel, ProFilter, Dialog },
  extends: page,
  props: {
    reqList: {
      default: purchases,
      type: Function,
    },
  },
  data() {
    return {
      parameter: { state: 1 },
      price: {},
      price_summary: {},
      // types: [{ v: 1, l: '物料' }, { v: 2, l: '设备' }, { v: 3, l: '工程外包' }, { v: 4, l: '仓库' }],
      // dts: [{ v: 'y', l: '年份' }, { v: 'm', l: '月份' }, { v: 'd', l: '日期' }],
      filter: {
        // dt: 'm',
        // types: [1, 2, 3, 4]
        name: '',
        sup_id: '',
        id: '',
      },
      yearAmount: 0,
      monthAmount: 0,
      quarters: [],
      months: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getListBefore() {
      if (!(this.filter.year && this.filter.year != ''))
        this.$set(this.filter, 'year', new Date().getFullYear() + '')
    },
    formatterType(row) {
      let type = ''
      if (row.type === 1) {
        type = '物料采购'
      } else if (row.type === 2) {
        type = '设备采购'
      } else if (row.type === 3) {
        type = '工程外包'
      } else if (row.type === 4) {
        type = '库存出库'
      }
      return type
    },
    formatterCompany(row) {
      let company = ''
      if (row.company && row.company !== '') {
        company = row.company
      } else if (row.entrust_name && row.entrust_name !== '') {
        company = row.entrust_name
      } else if (row.type === 4) {
        company = '里欧总公司'
      }
      return company
    },
    getListAfter(e) {
      this.price_summary = e.summary
      this.handleAmount()
    },
    handleAmount() {
      purchaseTotalAmount({
        ...this.filter,
      })
        .then((res) => {
          this.price = res.info ? res.info : {}
          // this.yearAmount = res.yearAmount ? res.yearAmount : 0
          this.monthAmount = res.monthAmount ? res.monthAmount : 0
          this.quarters = res.quarters ? res.quarters : []
          this.months = res.months ? res.months : []

          this.handleSAmount()
          this.handleSNum()
        })
        .catch((err) => {
          this.$message.error(err.msg)
        })
    },
    handleSAmount() {
      var chart = document.getElementById('ba')
      var echart = echarts.init(chart)
      let x = []
      let y = []
      this.months.forEach((e) => {
        x.push(e['m'])
        y.push(e['price'])
      })
      x.push('合计')
      y.push(this.yearAmount)
      let option = {
        title: {
          text: '每月采购金额对比图',
          subtext: '',
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: x,
          axisLabel: {
            interval: 0,
            rotate: 20,
          },
        },
        yAxis: {},
        series: [
          {
            name: '金额',
            type: 'bar',
            data: y,
            itemStyle: {
              barBorderRadius: 0,
              color: '#73c0de',
              borderWidth: 0,
              borderType: 'solid',
              borderColor: '#73c0de',
              shadowColor: '#73c0de',
              shadowBlur: 0,
            },
            barWidth: '40%',
          },
        ],
      }
      echart.setOption(option)
      echart.getZr().on('click', (params) => {
        let pointInPixel = [params.offsetX, params.offsetY]
        if (echart.containPixel('grid', pointInPixel)) {
          let xIndex = echart.convertFromPixel({ seriesIndex: 0 }, [
            params.offsetX,
            params.offsetY,
          ])[0]
          let month =
            this.filter.year +
            '-' +
            (xIndex + 1 >= 10 ? xIndex + 1 : '0' + (xIndex + 1))
          this.handleDialog({
            ...{ month: month },
            ...{
              dRef: 'dialog',
              dTitle: '采购详情',
              dType: 'edit',
              dField: ['month'],
            },
          })
        }
      })
    },
    handleSNum() {
      var chart = document.getElementById('bn')
      var echart = echarts.init(chart)
      let x = []
      let y = []
      let len = this.quarters.length
      for (let i = 0; i < len; i++) {
        x.push(this.quarters[i]['q'])
        y.push(this.app.toFix(this.quarters[i]['price'] / 10000, 0))
      }
      let option = {
        title: {
          text: '季度采购金额对比图（万）',
          subtext: '',
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: x,
          axisLabel: {
            interval: 0,
            rotate: 20,
          },
        },
        grid: {
          top: 50,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true,
        },
        yAxis: {},
        series: [
          {
            name: '金额（万）',
            type: 'bar',
            data: y,
            itemStyle: {
              barBorderRadius: 0,
              color: '#73c0de',
              borderWidth: 0,
              borderType: 'solid',
              borderColor: '#73c0de',
              shadowColor: '#73c0de',
              shadowBlur: 0,
            },
            barWidth: '40%',
          },
        ],
      }
      echart.setOption(option)
    },
    getSummaries() {
      let price = this.price_summary.price ? this.price_summary.price : 0
      let additional = this.price_summary.additional
        ? this.price_summary.additional
        : 0
      let reduction = this.price_summary.reduction
        ? this.price_summary.reduction
        : 0
      let pay = this.price_summary.pay ? this.price_summary.pay : 0
      let has_tax = this.price_summary.has_tax ? this.price_summary.has_tax : 0

      this.yearAmount = this.app.toFix(price + additional - reduction, 2)

      const sums = []
      sums[0] = '合计'
      sums[1] = ''
      sums[2] = ''
      sums[3] = ''
      sums[4] = ''
      sums[5] = ''
      sums[6] = this.app.toFix(price + additional - reduction, 2)
      sums[7] = this.app.toFix(pay, 2)
      sums[8] = this.app.toFix(price - pay + additional - reduction, 2)
      sums[9] = this.app.toFix(additional, 2)
      sums[10] = this.app.toFix(reduction, 2)
      sums[11] = this.app.toFix(has_tax, 2)
      sums[12] = this.app.toFix(price - has_tax, 2)
      return sums
    },
  },
}
</script>
<style scoped>
.m-left {
  width: 180px;
}
.m-left-title {
  padding: 10px;
  height: 70px;
  line-height: 1.2;
  border-radius: 6px;
  color: #ffffff;
}
.m-center {
  padding-left: 210px;
  padding-right: 320px;
}
.m-right {
  width: 310px;
}
</style>
